# coding: utf-8
import socket
import mainget_data

'''
读取客户端传来的长域名
返回数据短域名+id

读取客户端传来的短域名+id
返回数据长域名

'''


def custom_html():
    sk = socket.socket()
    sk.bind(('127.0.0.1', 9999))
    sk.listen(5)
    print('sever is listening on port: 9999')

    while True:
        print('-------------------')
        client_connection, client_address = sk.accept()
        print('link addr:' + str(client_address))  # 打印客户端发来的嵌套字
        data = client_connection.recv(1024)
        temp_str = data.decode('utf8')
        print(temp_str)
        # print('-------------------')

        temp_arr = temp_str.split('\n');

        cleand_URL = cleanURL(str(temp_arr[0]))

        checkURL(cleand_URL)

        with open('test.json', 'rb') as f:
            html_data = f.read()

        # SEND URL
        client_connection.send(bytes('HTTP/1.1 201 OK\r\n' + 'Access-Control-Allow-Origin:* \r\n' + 'Connection: close\r\n\r\n', 'utf8'))
        client_connection.sendall(html_data)
        client_connection.close()


def cleanURL(head):
    tstr = head
    tstr0 = tstr.replace('HTTP/1.1', '')
    tstr1 = tstr0.replace('GET /', '')
    return tstr1


def checkURL(head):
    temp_str = cleanURL(str(head))
    if temp_str[:4] == '?ID=':
        print('recive id ,return url')
        temp_str0 = temp_str.replace('?ID=', '')
        temp_str0 = temp_str0.replace(' \r', '')
        rst_URL = mainget_data.get_URL(str(temp_str0))
        write_json(rst_URL)
    elif temp_str[:5] == '?URL=':
        print('recive url ,add id,return short url')
        temp_str0 = temp_str.replace('?URL=', '')
        this_url = mainget_data.add_json(temp_str0)
        write_json(this_url)

    elif temp_str[:3] == 'fav':
        print('require favicon.ico')
        write_json('https://lo-li.cn/wp-content/uploads/2019/01/ZeroDream-Logo-Single-White-Main.png')

    elif temp_str == '':
        print('no require' + temp_str)
        write_json('none')
    else:
        print('error require' + temp_str)
        write_json('none')


def write_json(rst_URL):
    with open(r'test.json', 'r+') as f5:
        f5.truncate()
        content = str(rst_URL)
        f5.write('{ "URL":"' + content + '"}')


if __name__ == '__main__':
    custom_html()
